package com.ruoyi.system.pay.config;

import com.ruoyi.system.pay.mapper.PayConfigMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 动态加载支付配置
 */
@Slf4j
@Component
public class PayConfigLoader {

    @Autowired
    private PayConfigMapper payConfigMapper;

    /**
     * 支付配置缓存
     */
    private static final Map<String, String> CONFIG_CACHE = new HashMap<>();

    /**
     * 初始化加载支付配置
     */
    @PostConstruct
    public void loadConfig() {
        log.info("初始化加载支付配置信息...");
        List<Map<String, String>> configs = payConfigMapper.selectAllConfigs();
        configs.forEach(config -> CONFIG_CACHE.put(config.get("config_key"), config.get("config_value")));
    }

    /**
     * 根据 Key 获取配置
     *
     * @param key 配置 Key
     * @return 配置值
     */
    public String getConfig(String key) {
        return CONFIG_CACHE.get(key);
    }

    /**
     * 更新配置
     *
     * @param key   配置 Key
     * @param value 配置值
     */
    public void updateConfig(String key, String value) {
        payConfigMapper.updateConfig(key, value);
        CONFIG_CACHE.put(key, value);
    }
}
